<template>
  <basePages>
    <view class="detail-container">
      <!-- 基本信息卡片 -->
      <view class="info-card">
        <view class="card-title">基本信息</view>
        <view class="info-item" @click="openEdit('name')">
          <text class="item-label">姓名</text>
          <view class="item-content">
            <text class="item-value">{{ elderlyData.name || '未设置' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>

        <view class="info-item" @click="openEdit('age')">
          <text class="item-label">年龄</text>
          <view class="item-content">
            <text class="item-value">{{ elderlyData.age || '未设置' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>

        <view class="info-item" @click="openEdit('phone')">
          <text class="item-label">手机号</text>
          <view class="item-content">
            <text class="item-value">{{ formatPhone(elderlyData.phone) || '未绑定' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>
      </view>

      <!-- 健康状态卡片 -->
      <view class="health-card">
        <view class="card-title">健康状态</view>
        <view class="health-status">
          <view class="status-item">
            <text class="label">血压</text>
            <text class="value" :class="getBloodPressureClass(elderlyData.bloodPressure)">
              {{elderlyData.bloodPressure || '--'}}
            </text>
            <text class="unit">mmHg</text>
            <text class="status-text" :class="getBloodPressureClass(elderlyData.bloodPressure)">
              {{getBloodPressureStatus(elderlyData.bloodPressure)}}
            </text>
          </view>
          <view class="status-item">
            <text class="label">心率</text>
            <text class="value" :class="getHeartRateClass(elderlyData.heartRate)">
              {{elderlyData.heartRate || '--'}}
            </text>
            <text class="unit">次/分</text>
            <text class="status-text" :class="getHeartRateClass(elderlyData.heartRate)">
              {{getHeartRateStatus(elderlyData.heartRate)}}
            </text>
          </view>
          <view class="status-item">
            <text class="label">血氧</text>
            <text class="value" :class="getBloodOxygenClass(elderlyData.bloodOxygen)">
              {{elderlyData.bloodOxygen || '--'}}
            </text>
            <text class="unit">%</text>
            <text class="status-text" :class="getBloodOxygenClass(elderlyData.bloodOxygen)">
              {{getBloodOxygenStatus(elderlyData.bloodOxygen)}}
            </text>
          </view>
        </view>
      </view>

      <!-- 过敏药物卡片 -->
      <view class="allergy-card">
        <view class="card-header">
          <text class="card-title">过敏药物</text>
          <view class="add-btn" @click="showAddAllergy">
            <text class="add-icon">+</text>
            <text class="add-text">添加</text>
          </view>
        </view>
        <view class="allergy-list">
          <view v-if="!allergyList || allergyList.length === 0" class="empty-tip">
            暂无过敏药物记录
          </view>
          <view v-else class="allergy-item" v-for="(item, index) in allergyList" :key="index">
            <view class="medicine-info">
              <text class="medicine-name">{{item.medicationName}}</text>
              <text class="medicine-desc">{{item.drugDiscription}}</text>
            </view>
            <view class="delete-btn" @click="deleteAllergy(index)">删除</view>
          </view>
        </view>
      </view>

      <!-- 编辑弹窗 -->
      <uni-popup ref="editPopup" type="dialog">
        <uni-popup-dialog
          mode="base"
          :title="editTitle"
          @confirm="submitForm"
          @close="closeEdit"
        >
          <uni-forms :model="editForm" :rules="formRules" ref="formRef">
            <uni-forms-item label="姓名" name="name">
              <uni-easyinput v-model="editForm.name" placeholder="请输入姓名" />
            </uni-forms-item>
            <uni-forms-item label="年龄" name="age">
              <uni-easyinput v-model="editForm.age" type="number" placeholder="请输入年龄" />
            </uni-forms-item>
            <uni-forms-item label="手机号" name="phone">
              <uni-easyinput v-model="editForm.phone" type="number" placeholder="请输入手机号" />
            </uni-forms-item>
          </uni-forms>
        </uni-popup-dialog>
      </uni-popup>

      <!-- 添加过敏药物弹窗 -->
      <uni-popup ref="allergyPopup" type="dialog">
        <uni-popup-dialog
          mode="base"
          title="添加过敏药物"
          @confirm="submitAllergy"
          @close="closeAllergy"
        >
          <uni-forms :model="allergyForm" :rules="allergyRules" ref="allergyFormRef">
            <uni-forms-item label="药物名称" name="name">
              <uni-easyinput v-model="allergyForm.name" placeholder="请输入药物名称" />
            </uni-forms-item>
            <uni-forms-item label="过敏描述" name="description">
              <uni-easyinput v-model="allergyForm.description" placeholder="请输入过敏症状描述" />
            </uni-forms-item>
          </uni-forms>
        </uni-popup-dialog>
      </uni-popup>
    </view>
  </basePages>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useHealthData } from '../../../store/modules/useHealthData'
import { useRecordStore } from '../../../store/modules/useRecordStore'
import { useBindingStore } from '../../../store/modules/useBindingStore'

const healthData = useHealthData()
const recordStore = useRecordStore()
const bindingStore = useBindingStore()

// 页面数据
const elderlyData = ref({
  id: null,
  name: '',
  age: '',
  phone: '',
  avatar: '',
  bloodPressure: '',
  heartRate: '',
  bloodOxygen: '',
  healthStatus: ''
})

// 过敏药物列表
const allergyList = ref([])

// 编辑表单数据
const editForm = ref({
  name: '',
  age: '',
  phone: ''
})

// 过敏药物表单数据
const allergyForm = ref({
  name: '',
  description: ''
})

// 弹窗引用
const editPopup = ref(null)
const allergyPopup = ref(null)
const formRef = ref(null)
const allergyFormRef = ref(null)

// 当前编辑字段
const currentField = ref('all')

// 计算属性
const editTitle = computed(() => currentField.value === 'all' 
  ? '编辑基本信息' 
  : `修改${getFieldLabel(currentField.value)}`
)

// 表单验证规则
const formRules = {
  name: { rules: [{ required: true, errorMessage: '请输入姓名' }] },
  age: {
    rules: [
      { required: true, errorMessage: '请输入年龄' },
      { format: 'number', errorMessage: '必须为数字' }
    ]
  },
  phone: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
    ]
  }
}

// 过敏药物表单验证规则
const allergyRules = {
  name: { rules: [{ required: true, errorMessage: '请输入药物名称' }] },
  description: { rules: [{ required: true, errorMessage: '请输入过敏症状描述' }] }
}

// 初始化加载数据
onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const elderlyId = currentPage.options?.id

  if (elderlyId) {
    try {
      
      // 获取绑定列表
      await bindingStore.fetchBindingList()
      const bindingList = bindingStore.getBindingList
      
      // 获取老人基本信息
      const elderlyInfo = bindingList.find(item => item.id === Number(elderlyId))
      
      if (elderlyInfo) {
        elderlyData.value = {
          ...elderlyData.value,
          id: elderlyInfo.id,
          name: elderlyInfo.name,
          age: elderlyInfo.age,
          phone: elderlyInfo?.phone|| '---', 
          avatar: elderlyInfo?.avatar || 'static/logo.png',
        }
      }

      // 获取实时健康数据
      const realtimeData = await healthData.fetchRealtimeData(elderlyId)
      console.log('实时健康数据:', realtimeData)
      
      elderlyData.value = {
        ...elderlyData.value,
        bloodPressure: `${realtimeData.bloodPressureHigh}/${realtimeData.bloodPressureLow}`,
        heartRate: realtimeData.heartRate,
        bloodOxygen: realtimeData.bloodOxygen,
        healthStatus: realtimeData.healthStatus
      }

      // 获取过敏药物列表
      recordStore.setCurUserId(elderlyId)
      const res = await recordStore.fetchAllergyList(elderlyId)
      allergyList.value = recordStore.getAllergyList
  
    } catch (err) {
      console.error('数据加载失败:', err)
      uni.showToast({ title: '数据加载失败', icon: 'none' })
    }
  }
})

// 打开编辑弹窗
const openEdit = (field) => {
  currentField.value = field
  initEditForm()
  editPopup.value.open()
}

// 初始化表单数据
const initEditForm = () => {
  if (currentField.value === 'all') {
    editForm.value = { ...elderlyData.value }
  } else {
    editForm.value = { [currentField.value]: elderlyData.value[currentField.value] }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const validate = await formRef.value.validate()
    if (!validate) return
    
    const updatedData = currentField.value === 'all' 
      ? { ...editForm.value }
      : { [currentField.value]: editForm.value[currentField.value] }
    
    // 使用正确的接口更新用户信息
    const res = await post('/users/update', {
      userId: elderlyData.value.id,
      ...updatedData
    }, 'api/v1');
    
    if (res && res.code === 200) {
      elderlyData.value = { ...elderlyData.value, ...updatedData }
      uni.showToast({ title: '更新成功', icon: 'success' })
    } else {
      throw new Error(res?.msg || '更新失败')
    }
    
    editPopup.value.close()
  } catch (err) {
    console.error('更新失败:', err)
    uni.showToast({ title: '更新失败', icon: 'none' })
  }
}


// 关闭编辑弹窗
const closeEdit = () => {
  editForm.value = { name: '', age: '', phone: '' }
  editPopup.value.close()
}

// 显示添加过敏药物弹窗
const showAddAllergy = () => {
  allergyForm.value = { name: '', description: '' }
  allergyPopup.value.open()
}

// 提交过敏药物
const submitAllergy = async () => {
  try {
    const validate = await allergyFormRef.value.validate()
    if (!validate){
      uni.showToast({ title: '请填写完整信息', icon: 'none' })
      return
    } 
    
    const newAllergy = { 
      medicationName: allergyForm.value.name,
      drugDiscription: allergyForm.value.description,
      allergy: true
    }
    console.log('添加过敏药物:', newAllergy)
    
    await recordStore.addAllergy(newAllergy)
    // Refetch the complete list after adding
    await recordStore.fetchAllergyList(elderlyData.value.id)
    allergyList.value = recordStore.getAllergyList.value
    
    uni.showToast({ title: '添加成功', icon: 'success' })
    allergyPopup.value.close()
  } catch (err) {
    console.error('添加失败:', err)
    uni.showToast({ 
      title: err.message || '添加失败', 
      icon: 'none',
      duration: 2000
    })
  }
}

// 删除过敏药物
const deleteAllergy = async (index) => {
  try {
    const allergyId = allergyList.value[index].id
    await recordStore.delAllergy(allergyId)
    // Refetch the complete list after deleting
    await recordStore.fetchAllergyList(elderlyData.value.id)
    allergyList.value = recordStore.getAllergyList.value
    uni.showToast({ title: '删除成功', icon: 'success' })
  } catch (err) {
    console.error('删除失败:', err)
    uni.showToast({ 
      title: err.message || '删除失败', 
      icon: 'none',
      duration: 2000
    })
  }
}

// 关闭过敏药物弹窗
const closeAllergy = () => {
  allergyForm.value = { name: '', description: '' }
  allergyPopup.value.close()
}

// 字段标签映射
const getFieldLabel = (field) => {
  const labels = {
    name: '姓名',
    age: '年龄',
    phone: '手机号'
  }
  return labels[field] || ''
}

// 手机号格式化
const formatPhone = (phone) => {
  return phone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') || '未绑定'
}

// 健康状态相关方法
const getBloodPressureClass = (value) => {
  if (!value) return '';
  const [systolic, diastolic] = value.split('/').map(Number);
  if (systolic > 140 || diastolic > 90) return 'warning';
  if (systolic < 90 || diastolic < 60) return 'warning';
  return 'normal';
};

const getHeartRateClass = (value) => {
  if (!value) return '';
  const rate = Number(value);
  if (rate > 100 || rate < 60) return 'warning';
  return 'normal';
};

const getBloodOxygenClass = (value) => {
  if (!value) return '';
  const oxygen = Number(value);
  if (oxygen < 95) return 'warning';
  return 'normal';
};

const getBloodPressureStatus = (value) => {
  if (!value) return '--';
  const [systolic, diastolic] = value.split('/').map(Number);
  if (systolic > 140 || diastolic > 90) return '偏高';
  if (systolic < 90 || diastolic < 60) return '偏低';
  return '正常';
};

const getHeartRateStatus = (value) => {
  if (!value) return '--';
  const rate = Number(value);
  if (rate > 100) return '偏快';
  if (rate < 60) return '偏慢';
  return '正常';
};

const getBloodOxygenStatus = (value) => {
  if (!value) return '--';
  const oxygen = Number(value);
  if (oxygen < 95) return '偏低';
  return '正常';
};
</script>

<style lang="scss">
.detail-container {
  min-height: 100vh;
  background-color: #F5F9FF;
  padding: 30rpx;
  
  .info-card, .health-card, .allergy-card {
    background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(41, 135, 254, 0.08);
    
    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      padding-left: 20rpx;
      border-left: 8rpx solid #2987FE;
    }
  }

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #F0F7FF;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-label {
      font-size: 30rpx;
      color: #333;
    }
    
    .item-content {
      display: flex;
      align-items: center;
      
      .item-value {
        margin-right: 20rpx;
        color: #666;
        font-size: 30rpx;
        max-width: 400rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .arrow-right {
        width: 16rpx;
        height: 16rpx;
        border-top: 2rpx solid #2987FE;
        border-right: 2rpx solid #2987FE;
        transform: rotate(45deg);
      }
    }
    
    &:active {
      opacity: 0.8;
    }
  }

  .health-status {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;

    .status-item {
      text-align: center;
      flex: 1;
      position: relative;

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1rpx;
        height: 60%;
        background-color: rgba(41, 135, 254, 0.1);
      }

      .label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 12rpx;
        display: block;
      }

      .value {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
        display: block;
        transition: all 0.3s ease;

        &.normal {
          color: #4caf50;
        }

        &.warning {
          color: #f44336;
        }
      }

      .unit {
        font-size: 22rpx;
        color: #999;
        margin-bottom: 8rpx;
        display: block;
      }

      .status-text {
        font-size: 22rpx;
        display: block;

        &.normal {
          color: #4caf50;
        }

        &.warning {
          color: #f44336;
        }
      }
    }
  }

  .allergy-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .add-btn {
        display: flex;
        align-items: center;
        padding: 8rpx 20rpx;
        background: rgba(41, 135, 254, 0.1);
        border-radius: 30rpx;
        transition: all 0.3s ease;

        &:active {
          background: rgba(41, 135, 254, 0.2);
        }

        .add-icon {
          font-size: 28rpx;
          color: #2987FE;
          margin-right: 8rpx;
        }

        .add-text {
          font-size: 26rpx;
          color: #2987FE;
        }
      }
    }

    .allergy-list {
      .empty-tip {
        text-align: center;
        color: #999;
        padding: 40rpx 0;
      }

      .allergy-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background: #fff;
        border-radius: 12rpx;
        margin-bottom: 20rpx;

        .medicine-info {
          flex: 1;
          margin-right: 20rpx;

          .medicine-name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 8rpx;
            display: block;
          }

          .medicine-desc {
            font-size: 24rpx;
            color: #666;
          }
        }

        .delete-btn {
          padding: 8rpx 20rpx;
          background: rgba(244, 67, 54, 0.1);
          color: #f44336;
          border-radius: 20rpx;
          font-size: 24rpx;
          transition: all 0.3s ease;

          &:active {
            background: rgba(244, 67, 54, 0.2);
          }
        }
      }
    }
  }
}
</style> 